package com.smartwebx.ha.web.util.json.module;

import java.io.IOException;
import java.math.BigDecimal;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;

/**
 * 保留一位小时
 * 
 * @author Administrator
 * 
 */
public class DoubleSerializer extends JsonSerializer<Double> {
	int roundingMode = 4;// 表示四舍五入，可以选择其他舍值方式，例如去尾，等等.
	int scale = 1;
	boolean isNumber = false;

	public DoubleSerializer() {

	}

	public DoubleSerializer(int scale, boolean isNumber) {
		this.scale = scale;
		this.isNumber = isNumber;
	}

	@Override
	public void serialize(Double value, JsonGenerator jgen,
			SerializerProvider provider) throws IOException,
			JsonProcessingException {
		if (Double.isNaN(value) || Double.isInfinite(value) || value == 0d) {
			if (isNumber) {
				jgen.writeNumber(0d);
			} else {
				jgen.writeString("0.0");
			}
			return;
		}
		BigDecimal bd = new BigDecimal(value);
		bd = bd.setScale(scale, roundingMode);
		String tx = bd.toString();
		if (isNumber) {
			jgen.writeNumber(tx);
		} else {
			jgen.writeString(tx);
		}
	}

}
